<template>
    <div class="index-top">
        <div class="top-location" @click="showLocation">
            <slot name="location">
            </slot>
            <div class="local-text">
                <img src="/static/img/index/local_icon.png">
                {{area.cityName}}
                <img class="local_more" :class="{ 'arrowTransform': !flag, 'arrowTransformReturn': flag}" src="/static/img/index/local_more.png">
            </div>
            <div class="down-pull">（下拉）</div>
        </div>
        <van-popup @close="closeLocation" v-model="isAreaList" position="bottom" get-container="#app">
          <van-area cancel-button-text="定位当前位置" :value="currentCityCode" :columns-num="2" :area-list="areaList" @confirm="confirmArea" @cancel="cancelLocation" :columns-placeholder="['请选择', '请选择']" />
        </van-popup>
        <div class="top-input">
            <slot name="search_input">
            </slot>
            <div class="input_div" @click="goToSearch">
                <img src="/static/img/search_icon.png">
                <div>{{area.cityName}}</div>
            </div>
        </div>
        <div class="top-msg">
          <slot name="message">
              <slot name="blank_div"></slot>
              <div class="top-message" @click="goToNotice">
                  <img src="/static/img/index/message.png">
              </div>
          </slot>
      </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import BMap from 'BMap';
import areaList from '@/plugins/areaList';
export default {
  name: 'head-search',
  data () {
    return {
      flag: true,
      areaList,
      isAreaList: false,
      addComp: {},
      address: '',
      currentCityCode: '',
      area: {
        provName: '',
        cityName: '全国',
        areaName: '',
        provCode: '',
        cityCode: '',
        areaCode: '',
        lat: '',
        lng: ''
      },
      logoUrl: './static/img/index/logo.png'
    };
  },
  props: {
    value: {
      type: Number
    },
    searchType: {
      type: String
    }
  },
  computed: {
    ...mapGetters(['currentLocal'])
  },
  mounted () {
    this.confirmLocation();
    // this.getCurrentLocation();
  },
  methods: {
    confirmLocation() {
      let that = this;
      let temp = localStorage.getItem('isShowConfirm');
      let areaInfo = JSON.parse(localStorage.getItem('areaInfo'));
      if (temp && temp === '1') { // 第一次点了确定定位
        return;
      } else if (temp && temp === '2') { // 第一次点了取消定位
        if (!areaInfo) {
          let tempObj = {};
          tempObj.provCode = '';
          tempObj.cityCode = '';
          // tempObj.areaCode = '';
          tempObj.lat = '';
          tempObj.lng = '';
          that.$emit('areaInfo', tempObj);
        } else {
          that.area.cityName = areaInfo.cityName;
          that.currentCityCode = areaInfo.cityCode;
          that.$emit('areaInfo', areaInfo);
        }
        return;
      }
      that.$dialog.confirm({
        title: '定位',
        message: '请问需要定位当前位置吗',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        that.getCurrentLocation();
        localStorage.setItem('isShowConfirm', 1);
      }).catch(() => {
        let tempObj = {};
        tempObj.provCode = '';
        tempObj.cityCode = '';
        // tempObj.areaCode = '';
        tempObj.lat = '';
        tempObj.lng = '';
        that.$emit('areaInfo', tempObj);
        localStorage.setItem('isShowConfirm', 2);
      });
    },
    goToNotice() {
      this.$router.push({ 'path': '/announcement/list' });
    },
    goToSearch() {
      this.$router.push({ 'path': 'index/search', query: { searchType: this.searchType } });
    },
    showLocation() {
      let that = this;
      that.isAreaList = true;
      that.flag = false;
    },
    closeLocation() {
      let that = this;
      that.flag = true;
    },
    // 获取当前位置
    getCurrentLocation() {
      let that = this;
      if (localStorage.getItem('areaInfo')) { // 判断是否存储过当前位置,如果有则停止以下操作
        let tempObj = JSON.parse(localStorage.getItem('areaInfo'));
        that.area.cityName = tempObj.cityName;
        that.currentCityCode = tempObj.cityCode;
        that.$emit('areaInfo', tempObj);
        return;
      }
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r) {
        // eslint-disable-next-line no-undef
        if (this.getStatus() === BMAP_STATUS_SUCCESS) {
          let point = new BMap.Point(r.point.lng, r.point.lat);
          let gc = new BMap.Geocoder();
          gc.getLocation(point, function(rs) {
            that.addComp = rs.addressComponents;// 当前地址对象
            that.address = rs.address;
          });
          setTimeout(function() {
            // 获得当前位置的省市区
            that.area.provName = that.addComp.province;
            that.area.cityName = that.addComp.city;
            that.area.areaName = that.addComp.district;
            // 获得当前位置的经纬度
            that.area.lng = r.point.lng;
            that.area.lat = r.point.lat;
            // 通过当前定位的地址寻找出对应的编码
            for (let i in that.areaList.province_list) {
              let temp = that.areaList.province_list[i];
              if (temp.indexOf(that.addComp.province) !== -1) {
                that.area.provCode = i;
              }
            }
            for (let i in that.areaList.city_list) {
              let temp = that.areaList.city_list[i];
              if (temp.indexOf(that.addComp.city) !== -1) {
                that.area.cityCode = i;
              }
            }
            // for (let i in that.areaList.county_list) {
            //   let temp = that.areaList.county_list[i];
            //   if (that.addComp.district) { // 如果有地区
            //     if (temp.indexOf(that.addComp.district) !== -1) {
            //       that.area.areaCode = i;
            //       that.currentCityCode = i;
            //     }
            //   } else {
            //     if (temp.indexOf(that.addComp.street.substr(0, 2)) !== -1) {
            //       that.area.areaCode = i;
            //       that.area.areaName = temp;
            //       that.currentCityCode = i;
            //     }
            //   }
            // }
            localStorage.setItem('areaInfo', JSON.stringify(that.area));
            that.$emit('areaInfo', that.area);
          }, 2000);
        } else {
          alert('failed' + this.getStatus());
        }
      }, { enableHighAccuracy: true });
    },
    cancelLocation (el, data) {
      let that = this;
      that.isAreaList = false;
      console.log('重新定位');
      this.$toast.loading({ duration: 2000 });
      localStorage.removeItem('areaInfo');
      that.getCurrentLocation();
    },
    confirmArea (data) {
      let that = this;
      var province = data[0] && data[0];
      var city = data[1] && data[1];
      // var county = data[2] && data[2];
      if (!province.name) {
        that.$toast('请选择省');
        return;
      }
      if (!city.name) {
        that.$toast('请选择市');
        return;
      }
      // if (!county.name) {
      //   that.$toast('请选择区');
      // }
      that.area.provName = province && province.name;
      that.area.cityName = city && city.name;
      // that.area.areaName = county && county.name;
      that.area.provCode = province && province.code;
      that.area.cityCode = city && city.code;
      // that.area.areaCode = county && county.code;
      that.currentCityCode = city && city.code;
      localStorage.setItem('areaInfo', JSON.stringify(that.area));
      that.$emit('areaInfo', that.area);
      that.isAreaList = false;
    }
  }
};
</script>
<style scoped lang="less">
.index-top{
    width:100%;
    display: flex;
    flex-wrap:nowrap;
    align-items: center;
    height:110px;
    margin:10px 0;
    .top-location{
      height:auto;
      text-align: center;
      img{
        width:60px;
      }
      .local-text{
        width:100%;
        height:30px;
        display: flex;
        flex-wrap:nowrap;
        align-items: center;
        color:#343434;
        font-weight: bold;
        font-size: 25px;
        justify-content: space-around;
        padding: 0 15px;
        img{
          width:30px;
        }
        .local_more{
          width:20px;
        }
        .arrowTransform{
          transition: 0.2s;
          transform-origin: center;
          transform: rotateZ(180deg);
        }
        .arrowTransformReturn{
          transition: 0.2s;
          transform-origin: center;
          transform: rotateZ(0deg);
        }
      }
      .down-pull{
        color:#ccc;
        font-size: 20px;
      }
    }
    .top-input{
      flex:1;
      height:110px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .article_p{
        width:100%;
        height:45%;
        display:flex;
        align-items: center;
        color:#FF733E;
        font-size: 16px;
      }
      .input_div{
          width:100%;
          height:71.5px;
          position: relative;
        div{
          line-height: 71.5px;
          width:100%;
          height:100%;
          padding-left:60px;
          border-radius: 50px;
          background: #F4F4F4;
          border:none;
          color:#BABABA;
        }
        img{
          position: absolute;
          left:20px;
          width:30px;
          top:50%;
          transform: translate(0,-50%);
        }
      }
    }
    .top-msg{
      width:14%;
      height:110px;
      display: flex;
      align-items: center;
      flex-wrap:wrap;
      .blank_div{
        width:100%;
        height:49.5px;
      }
      .top-message{
        width:100%;
        height:71.5px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        img{
          width:40px;
        }
      }
    }
}
</style>
